package leetcode

import (
	"gitee.com/ombak/leetcode/pkg/list"
)

// https://leetcode.com/problems/reverse-linked-list-ii/
func ReverseBetween(head *list.ListNode, left int, right int) *list.ListNode {
	if left == 1 {
		return reverseN(head, right)
	}
	head.Next = ReverseBetween(head.Next, left-1, right-1)
	return head
}

var successor *list.ListNode

func reverseN(head *list.ListNode, n int) *list.ListNode {
	if n == 1 {
		successor = head.Next
		return head
	}
	last := reverseN(head.Next, n-1)
	head.Next.Next = head
	head.Next = successor
	return last
}
